package m5;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //建立连接
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        f.setPort(5672);//默认端口可以不设置
        f.setUsername("admin");
        f.setPassword("admin");
        Channel c = f.newConnection().createChannel();

        //定义独占的随机队列，定义交换机，用绑定键绑定
        //由服务器随机命名,其他参数默认值
        String queue = c.queueDeclare().getQueue();
        c.exchangeDeclare("topic_logs", BuiltinExchangeType.TOPIC);

        System.out.println("输入绑定键，用空格隔开：");
        String s = new Scanner(System.in).nextLine();
        String[] a = s.split("\\s+");
        for (String key : a) {
            c.queueBind(queue, "topic_logs", key);
        }

        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                String key = message.getEnvelope().getRoutingKey();
                System.out.println(key+"---"+msg);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };

        //从随机队列接收消息
        c.basicConsume(queue, true,deliverCallback,cancelCallback);
    }
}
